﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using dhDataAcess.produceDAL;
using dhSystemBLL.produceBLL;
using dhSystemBLL.basicData;
using baseSet.importExport;
using dhDataAcess.dataAcess.purchaseTableAdapters;
using dhDataAcess.dataAcess;
using baseSet;
using dhDataAcess.produceLinq;
using dhDataAcess.baseBLL;
using dhSystemBLL.orderData;
using dhsystem.Main;
using FastReport;

namespace dhsystem.produceForm
{
    public partial class FrmcgddMasterAdd : Form
    {
        
        purchase.cgddDetailDataTable cgddDetailTable = new purchase.cgddDetailDataTable();
        cgddDetailModel cgddDetailRow = new cgddDetailModel();
        cgddBLL cgdd = new cgddBLL();
        supplierListBLL supplier = new supplierListBLL();
        cgddMasterModel cgddMasterRow = new cgddMasterModel();
        deptBLL dept = new deptBLL();
        workerListBLL workerList = new workerListBLL();
        BindingSource b2;
        string state;
        public FrmcgddMasterAdd(BindingSource b1, string _state)
        {
            InitializeComponent();
            state = _state;
            b2 = b1;
        }
        //打开窗口时绑定数据
        private void FrmcgddMasterAdd_Load(object sender, EventArgs e)
        {
            textbillacount.Text = "0";
            bindingSourcedeptList.DataSource = dept.getdeptListAll();
            comboBoxdeptName.DataSource = bindingSourcedeptList;
            comboBoxdeptName.DisplayMember = "deptName";
            comboBoxdeptName.ValueMember = "deptNum";
            bindingSourceworkerList.DataSource = workerList.getworkerListAll();
            comboBoxworkername.DataSource = bindingSourceworkerList;
            comboBoxworkername.DisplayMember = "name";
            comboBoxworkername.ValueMember = "workerNum";
            bindingSourcesupplierList.DataSource = supplier.getsupplierListAll();
            comboBoxsNum.DataSource = bindingSourcesupplierList;
            comboBoxsNum.DisplayMember = "sName";
            comboBoxsNum.ValueMember = "sNum";
            if (state == "新增")
            {
                textbillNo.Text = "R" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("采购订单号");
                bindingSourcecgddDetail.DataSource = cgdd.getscgddDetailAllBybillNo(textbillNo.Text);
                dGridDetail.DataSource = bindingSourcecgddDetail;

            }
            if (state == "编辑")
            {

                comboBoxdeptName.DataBindings.Add("SelectedValue", b2, "deptName");
                comboBoxworkername.DataBindings.Add("SelectedValue", b2, "workername");
                textbillNo.DataBindings.Add("text", b2, "billNo");
                dateTimebillDate.DataBindings.Add("value", b2, "billDate");
                dateTimecomeDate.DataBindings.Add("value", b2, "comeDate");
                textbillacount.DataBindings.Add("text", b2, "billacount");
                comboBoxsNum.DataBindings.Add("SelectedValue", b2, "sNum");
                textmark.DataBindings.Add("text", b2, "mark");
                bindingSourcecgddDetail.DataSource = cgdd.getscgddDetailAllBybillNo(textbillNo.Text);
                dGridDetail.DataSource = bindingSourcecgddDetail;
            }
            DcolumnSet.colSet(moduleInfo.cgddDetail, dGridDetail);
           // dGridDetail.AllowUserToAddRows = false;
            dGridDetail.AllowUserToAddRows = true;
            this.KeyPreview = true;
            dGridDetail.EditMode = DataGridViewEditMode.EditOnEnter;
            comboBoxdeptName.Text = "采购部";
            comboBoxworkername.Text = "黄青云";
        }
        //int i = 0;
        //保存按钮，插入或修改数据
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (textbillNo.Text == "")
            {
                MessageBox.Show("请输入库单号");
            }
            else
            {
                try
                {
                    DialogResult result = MessageBox.Show("是否保存信息！", "提示信息", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        dhDataAcess.dataAcess.purchase.cgddDetailDataTable ptable = (dhDataAcess.dataAcess.purchase.cgddDetailDataTable)bindingSourcecgddDetail.DataSource;
                        cgddMasterRow.billNo = textbillNo.Text;
                        cgddMasterRow.deptName = comboBoxdeptName.SelectedValue.ToString();
                        cgddMasterRow.workername = comboBoxworkername.SelectedValue.ToString();
                        cgddMasterRow.billDate = dateTimebillDate.Value;
                        cgddMasterRow.comeDate = dateTimecomeDate.Value;
                        cgddMasterRow.billStatus = "新建";
                        cgddMasterRow.billacount  =Convert .ToDecimal( textbillacount.Text);
                        cgddMasterRow.sNum = comboBoxsNum.SelectedValue.ToString();
                        cgddMasterRow.createDate = DateTime.Now;
                        cgddMasterRow.createUser = GlobalInfo.UserName;
                        cgddMasterRow.updateDate = DateTime.Now;
                        cgddMasterRow.updateUser = GlobalInfo.UserName;
                        cgddMasterRow.mark = textmark.Text;
                        foreach (dhDataAcess.dataAcess.purchase.cgddDetailRow  a in ptable)
                        {
                            if (!a.IsfqtyNull())
                            {
                                a.fqty = a.fqty;
                            }
                            else { a.fqty = 0; }
                            var s = ptable.Where(x => x.matNum == a.matNum).ToList();
                            if (s.Count() > 1)
                            {
                                MessageBox.Show("存在两条相同产品名称的记录，不能保存");
                                return;
                            }
                            if (!a.IsqtyNull())
                            {
                                a.qty = a.qty;
                            }
                            else
                            {
                                DialogResult sresult = MessageBox.Show("数量为空是否保存！", "提示信息", MessageBoxButtons.YesNo);
                                if (sresult == DialogResult.Yes)
                                {
                                    a.qty = 0;
                                }
                                if (sresult == DialogResult.No)
                                {
                                    MessageBox.Show("保存已取消");
                                    return;
                                }
                            }
                        }
                        cgdd.cgddInsert(cgddMasterRow, ptable, state, textbillNo.Text, GlobalInfo.Date);
                        ptable.AcceptChanges();
                        bindingSourcecgddMaster.DataSource = cgdd.getcgddMasterAll();
                        MessageBox.Show("保存成功");
                    }
                }
                catch (FormatException ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
        }
        //取消按钮
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //删除子件
        private void buttDel_Click(object sender, EventArgs e)
        {
            try
            {
                string id = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[0].Value.ToString();
                DialogResult result = MessageBox.Show("是否删除：" + id + "！", "提示信息", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        //编辑子件
        private void buttedit_Click(object sender, EventArgs e)
        {
            FrmcgddDetailAdd cgddDetail = new FrmcgddDetailAdd(bindingSourcecgddDetail, "编辑", textbillNo.Text);
            cgddDetail.ShowDialog();
        }
        //添加子件
        private void buttAdd_Click(object sender, EventArgs e)
        {
            FrmcgddDetailAdd cgddDetail = new FrmcgddDetailAdd(bindingSourcecgddDetail, "新增", textbillNo.Text);
            cgddDetail.ShowDialog();
        }
       //选择采购部门
        private void buttuserselect_Click(object sender, EventArgs e)
        {
            string field;
            field = "deptNum";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.deptList, field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                comboBoxdeptName.SelectedValue = productselect.pname;
            }
        }
        //选择入库人
        private void button1_Click(object sender, EventArgs e)
        {
            string field;
            field = "workerNum";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.workerList, field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                comboBoxworkername.SelectedValue = productselect.pname;
            }
        }
        //选择供应商
        private void button2_Click(object sender, EventArgs e)
        {
            string field;
            field = "sNum";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.supplierList , field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                comboBoxsNum.SelectedValue = productselect.pname;
            }
        }

        private void comboBoxworkername_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void dGridDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            decimal acount = 0;
            if (dGridDetail.Rows.Count > 0 && e.RowIndex >= 0)
            {
                DataGridViewRow row = dGridDetail.Rows[e.RowIndex];
                if (row.Cells[e.ColumnIndex].OwningColumn.Name == "acount")
                {
                    try
                    {

                        for (int i = 0; i < dGridDetail.Rows.Count; i++)
                        {
                            try
                            {
                                acount += Convert.ToDecimal(dGridDetail.Rows[i].Cells["acount"].Value);

                            }
                            catch { }
                    
                        }

                        textbillacount.Text = acount.ToString();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }

        private void groupAdd_Enter(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dGridDetail_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
        {
            decimal decAmountTotal = 0;

            if (dGridDetail.Rows.Count > 0 && e.RowIndex >= 0)
            {
                DataGridViewRow row = dGridDetail.Rows[e.RowIndex];
                if (row.Cells[e.ColumnIndex].OwningColumn.Name == "matNum" || row.Cells[e.ColumnIndex].OwningColumn.Name == "qty" || row.Cells[e.ColumnIndex].OwningColumn.Name == "price")
                        {

                    try
                    {
                        row.Cells["matName"].Value = basicSql.getmatNamebymaterialList(row.Cells["matNum"].Value.ToString());
                        row.Cells["matSpec"].Value = basicSql.getmatSpecbymaterialList (row.Cells["matNum"].Value.ToString());
                        row.Cells["pihao"].Value = basicSql.getMatLotbymaterialList(row.Cells["matNum"].Value.ToString());
                        row.Cells["billNo"].Value = textbillNo.Text;
                        string acount;
                        if (row.Cells["price"].Value.ToString() != "" && row.Cells["qty"].Value.ToString() != "")
                        {
                            acount = (Convert.ToDecimal(row.Cells["qty"].Value) * Convert.ToDecimal(row.Cells["price"].Value)).ToString("#0.0000");
                            row.Cells["acount"].Value = acount;
                            row.Cells["acount"].ReadOnly = true;
                            for (int i = 0; i < dGridDetail.Rows.Count; i++)
                            {


                                decAmountTotal += Convert.ToDecimal(dGridDetail.Rows[i].Cells["acount"].Value);

                            }

                            textbillacount.Text = decAmountTotal.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }

        private void dGridDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string field;
            field = "matNum";
            int colIndex = dGridDetail.Columns["matNum"].Index;
            int colIndexmark = dGridDetail.Columns["mark"].Index;
            if (colIndex == e.ColumnIndex)
            {
                FrmcgddMark select = new FrmcgddMark(moduleInfo.materialList, field);
                DialogResult result = select.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = select.pname;
                }

            }
            if (colIndexmark == e.ColumnIndex)
            {
                Frmmark mark = new Frmmark();
                DialogResult result = mark.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = mark.mark;
                }
            }
        }
        /// <summary>  
        /// 设置编辑状态下按回车键，跳到指定单元格.  
        /// </summary>  
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            string field;
            field = "matNum";
            //cValue = dGridDetail.CurrentRow.Cells[3].EditedFormattedValue.ToString();
            if (keyData == Keys.Enter)    //监听回车事件   
            {
                if (this.dGridDetail.IsCurrentCellInEditMode)   //如果当前单元格处于编辑模式   
                {

                    if (this.dGridDetail.CurrentCell.ColumnIndex == 2)
                    {
                        //cValue= dGridDetail.CurrentRow.Cells[3].EditedFormattedValue.ToString();
                        Frmprodutselect select = new Frmprodutselect(moduleInfo.materialList, field);
                        DialogResult result = select.ShowDialog();
                        if (result == DialogResult.Yes)
                        {
                            //dGridDetail.CurrentCell.Value = select.pname;

                            dGridDetail.CurrentRow.Cells["matNum"].Value = select.pname;
                            //dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[4];
                        }
                    }

                    if (this.dGridDetail.CurrentCell.ColumnIndex != 10)
                    {
                        SendKeys.Send("{Up}");
                        SendKeys.Send("{Tab}");
                        // SendKeys.Send("{Tab}");
                    }

                    else
                    {
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                    }
                }
                else
                {
                    SendKeys.Send("{Up}");
                    SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                }


            }

            if (keyData == Keys.F3)
            {
                int cRowIndex = dGridDetail.CurrentCell.RowIndex;
                int cCellIndex = dGridDetail.CurrentCell.ColumnIndex;
                dGridDetail.CurrentCell.Value = dGridDetail.Rows[cRowIndex - 1].Cells[cCellIndex].Value;
                if (cCellIndex == 2 || cCellIndex == 0)
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex + 3];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
                else
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex - 1];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
            }

            //继续原来base.ProcessCmdKey中的处理   
            return base.ProcessCmdKey(ref msg, keyData);

        }

        private void buttprint_Click(object sender, EventArgs e)
        {
            //string billoNo = dGridyifp.CurrentRow.Cells["billoNo"].Value.ToString();
            Report r = new Report();
            DataSet ds = new DataSet();
            ds.Tables.Add(cgdd.getV_cgddbaobiaoAllBybillNo(textbillNo.Text));
            // r.Load(@"E:\东华软件项目\报表\cgddbaobiao.frx");
            r.Load(@"\\192.168.0.27\东华软件\报表\cgddbaobiao.frx");
            r.RegisterData(ds);
            //r.Design();
            r.Show();
        }

        private void toolExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolSave_Click(object sender, EventArgs e)
        {
            if (textbillNo.Text == "")
            {
                MessageBox.Show("请输入库单号");
            }
            else
            {
                try
                {
                    DialogResult result = MessageBox.Show("是否保存信息！", "提示信息", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        dhDataAcess.dataAcess.purchase.cgddDetailDataTable ptable = (dhDataAcess.dataAcess.purchase.cgddDetailDataTable)bindingSourcecgddDetail.DataSource;
                        cgddMasterRow.billNo = textbillNo.Text;
                        cgddMasterRow.deptName = comboBoxdeptName.SelectedValue.ToString();
                        cgddMasterRow.workername = comboBoxworkername.SelectedValue.ToString();
                        cgddMasterRow.billDate = dateTimebillDate.Value;
                        cgddMasterRow.comeDate = dateTimecomeDate.Value;
                        cgddMasterRow.billStatus = "新建";
                        cgddMasterRow.billacount = Convert.ToDecimal(textbillacount.Text);
                        cgddMasterRow.sNum = comboBoxsNum.SelectedValue.ToString();
                        cgddMasterRow.createDate = DateTime.Now;
                        cgddMasterRow.createUser = GlobalInfo.UserName;
                        cgddMasterRow.updateDate = DateTime.Now;
                        cgddMasterRow.updateUser = GlobalInfo.UserName;
                        cgddMasterRow.mark = textmark.Text;
                        foreach (dhDataAcess.dataAcess.purchase.cgddDetailRow a in ptable)
                        {
                            if (!a.IsfqtyNull())
                            {
                                a.fqty = a.fqty;
                            }
                            else { a.fqty = 0; }
                            var s = ptable.Where(x => x.matNum == a.matNum).ToList();
                            if (s.Count() > 1)
                            {
                                MessageBox.Show("存在两条相同产品名称的记录，不能保存");
                                return;
                            }
                            if (!a.IsqtyNull())
                            {
                                a.qty = a.qty;
                            }
                            else
                            {
                                DialogResult sresult = MessageBox.Show("数量为空是否保存！", "提示信息", MessageBoxButtons.YesNo);
                                if (sresult == DialogResult.Yes)
                                {
                                    a.qty = 0;
                                }
                                if (sresult == DialogResult.No)
                                {
                                    MessageBox.Show("保存已取消");
                                    return;
                                }
                            }
                        }
                        cgdd.cgddInsert(cgddMasterRow, ptable, state, textbillNo.Text, GlobalInfo.Date);
                        ptable.AcceptChanges();
                        bindingSourcecgddMaster.DataSource = cgdd.getcgddMasterAll();
                        MessageBox.Show("保存成功");
                    }
                }
                catch (FormatException ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
        }

        private void toolDel_Click(object sender, EventArgs e)
        {
            try
            {
                string id = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[0].Value.ToString();
                DialogResult result = MessageBox.Show("是否删除：" + id + "！", "提示信息", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void toolPrint_Click(object sender, EventArgs e)
        {
            //string billoNo = dGridyifp.CurrentRow.Cells["billoNo"].Value.ToString();
            Report r = new Report();
            DataSet ds = new DataSet();
            ds.Tables.Add(cgdd.getV_cgddbaobiaoAllBybillNo(textbillNo.Text));
            // r.Load(@"E:\东华软件项目\报表\cgddbaobiao.frx");
            r.Load(@"\\192.168.0.27\东华软件\报表\cgddbaobiao.frx");
            r.RegisterData(ds);
            //r.Design();
            r.Show();
        }

        private void toolAdd_Click(object sender, EventArgs e)
        {
            state = "新增";
            textbillNo.Text = "R" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("采购订单号");
            bindingSourcecgddDetail.DataSource = cgdd.getscgddDetailAllBybillNo(textbillNo.Text);
            dGridDetail.DataSource = bindingSourcecgddDetail;
            dGridDetail.AllowUserToAddRows = true;
            this.KeyPreview = true;
            dGridDetail.EditMode = DataGridViewEditMode.EditOnEnter;
            comboBoxdeptName.Text = "采购部";
            comboBoxworkername.Text = "黄青云";
            dateTimebillDate.Value = DateTime.Now;
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string billNo = textbillNo .Text;
            Report r = new Report();
            DataSet ds = new DataSet();
            ds.Tables.Add(cgdd.getV_cgddbaobiaoAllBybillNo(billNo));
            // r.Load(@"E:\东华软件项目\报表\cgddbaobiao.frx");
            r.Load(@"\\192.168.0.27\东华软件\报表\cgddbaobiao.frx");
            r.RegisterData(ds);
            //r.Design();
            r.Show();
        }
    }
}
